<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
    <title>title</title>
    <link rel="stylesheet" type="text/css" href="../css/api.css"/>
    <style>
        
    </style>
</head>
<body>
    <div class="wrap">
    </div>
</body>
<script type="text/javascript" src="../script/api.js"></script>
<!-- <script type="text/javascript" src="http://bit.liangzibiao.com/Public/Resource/js/socket.js"></script> -->
<script type="text/javascript" src="../script/common.js"></script>
<script type="text/javascript">

    var timer; // 定义定时器
    var timer1; // 定义定时器
    var GoogleMap; // 定义谷歌地图
    var i = 0; // i默认等于0
    var staffData = ''; // 定义骑手数据
    var newestTime = 0; // 在线时长，每分钟向数据库写入时统计的
    var socketManager;
    var locationSuccess = false; // 默认定位失败
    var tempTimer; // 定义默认定时器
    var tempSecond = 0; // 定义默认轮询的秒数 

    apiready = function(){
        staffData = $api.getStorage('staff_data');
        socketManager = api.require('socketManager');
        if(staffData){
            if(staffData.is_online == 1){
                // 先获取一次初始化的今日在线时长
                getInitOnlineTime();
                // 监听在线时长
                calculateOnlineTime();
            }
            getFirstStaffLocationFrequently(staffData);
            setInterval(function(){
                // 获取地理位置
                getStaffLocationFrequently(staffData);
            },30000);
        }
        var connectionType = api.connectionType;
        if(staffData && staffData.id && 'none' != connectionType){
            // accept_socket('staff_id'+staffData.id);
            fnConnectSocket();
        }

        api.addEventListener({
            name: 'loginSuccess'
        }, function(ret, err){
            if( ret ){
                staffData = $api.getStorage('staff_data');
                if(staffData){
                    if(staffData.is_online == 1){
                        // 先获取一次初始化的今日在线时长
                        getInitOnlineTime();
                        // 监听在线时长
                        calculateOnlineTime();
                    }
                    getFirstStaffLocationFrequently(staffData);
                    timer1 = setInterval(function(){
                        // 获取地理位置
                        getStaffLocationFrequently(staffData);
                    },30000);
                }
            }
        });

        api.addEventListener({
            name: 'reloadSocketEvent'
        }, function(ret, err){
            if( ret ){
                fnConnectSocket();
            }
        });

        api.addEventListener({
            name: 'reloadSocketEvent2'
        }, function(ret, err){
            if( ret ){
                clearInterval(timer1);
                fnCloseSocket();
            }
        });

        api.addEventListener({
            name: 'online'
        }, function(ret, err){
            if( ret ){
                fnConnectSocket();
                // window.location.reload();
            }
        });
        api.addEventListener({
            name: 'offline'
        }, function(ret, err){
            if( ret ){
                fnCloseSocket();
                // window.location.reload();
            }
        });

        api.addEventListener({
            name:'pause'
        }, function(ret, err){
            // clearInterval(timer);
            var demo = api.require('myTimer');
            demo.stopTimer(function(ret) {

            });
            var timestamp = parseInt((new Date()).valueOf()/1000)-i;
            $api.setStorage('pauseTime',timestamp);
            i = 0;
        });

        api.addEventListener({
            name:'resume'
        }, function(ret, err){
            staffData = $api.getStorage('staff_data');
            if(staffData){
                var timestamp = $api.getStorage('pauseTime');
                var timestamp2 = parseInt((new Date()).valueOf()/1000);
                var second = parseInt(timestamp2 - timestamp);
                if(staffData.is_online == 1){
                    // 补回之前的秒数
                    addSecond(second);
                    // 监听在线时长
                    calculateOnlineTime();
                }
                // 获取地理位置
                getStaffLocationFrequently(staffData);
            }
        });

        api.addEventListener({
            name: 'pauseTimer'
        }, function(ret, err){
            if( ret ){
                // 关闭开关时，把当前的时间i写入数据库
                addSecond(i);
                // 然后再关闭定时器
                i = 0;
                // clearInterval(timer);
                var demo = api.require('myTimer');
                demo.stopTimer(function(ret) {

                });
            }
        });

        api.addEventListener({
            name: 'continueTimer'
        }, function(ret, err){
            if( ret ){
                staffData = $api.getStorage('staff_data');
                calculateOnlineTime();
            }
        });

        api.addEventListener({
            name: 'updateNewestTime'
        }, function(ret, err){
            if( ret ){
                // $api.setStorage('newest_time',newestTime);
                var totalTime = parseInt(newestTime) + i;
                api.sendEvent({
                    name: 'toOpenStatusWin',
                    extra:{
                        totalTime: totalTime
                    }
                });
            }
        });
    };

    function fnConnectSocket () {
        staffData = $api.getStorage('staff_data');
        if(!staffData){
            return;
        }
        socketManager.createSocket({
            host: '13.250.39.107',
            port: 8282
        }, function(ret, err) {
            if(ret){
                if (ret.state == 103) {
                    if(ret.sid){
                        $api.setStorage('staff_sid', ret.sid);
                    }
                    if(ret.data){
                        var data = JSON.parse(ret.data);
                        if (data.type == 'init') {
                            api.ajax({
                                url: rootPath + '/workerMan/bind',
                                method: 'post',
                                data: {
                                    values: { 
                                        uid: 'staff_id'+staffData.id, // 这个需要传入真实的uid并加项目前缀
                                        client_id: data.client_id,
                                    },

                                }
                            });
                        } else if (data.flag == 'bit_rider') {
                            receive_fn(data);
                        }
                    }
                }
            }
        });
    };


    function fnCloseSocket () {
        socketManager.closeSocket({
            sid: $api.getStorage('staff_sid'),
        }, function(ret, err) {
            if (ret.status) {

            } else {

            }
        });
    };

    function getInitOnlineTime () {
        api.ajax({
            url: rootPath + '/api/staff/get_init_online_time',
            method: 'post',
            data: {
                values: { 
                    staff_id: staffData.id,
                    staff_token: staffData.token,
                },
            }
        }, function(ret, err) {
            if (ret && ret.status == 200) {
                newestTime = ret.data.online_time;
            }
        });
    };

    function getFirstStaffLocationFrequently (staffData) {
        /*$api.setStorage('staff_lng','113.5639583879277');
        $api.setStorage('staff_lat','22.28471991142471');*/
        tempSecond = 0;
        locationSuccess =false;
        var GoogleMap = api.require('googleMap');
        GoogleMap.getLocation(function(ret) {
            if (ret.status) {
                $api.setStorage('staff_lng',ret.lon);
                $api.setStorage('staff_lat',ret.lat);
                api.ajax({
                    url: rootPath + '/api/staff/update_log_lat',
                    method: 'post',
                    data: {
                        values: { 
                            staff_id: staffData.id,
                            staff_token: staffData.token,
                            lng: ret.lon,
                            lat: ret.lat
                        },
                    }
                }, function(ret2, err2) {
                    if( ret2 && ret2.status == 200){
                        locationSuccess = true;
                    }else{
                        locationSuccess = false;
                    }
                });
            }else{
                locationSuccess = false;
            }
        });
        // 因为getlocation没有回调返回，所以增加5秒判断是否定位成功
        tempTimer = setInterval(function(){
            if(locationSuccess == true){
                // 如果定位成功，则关闭定时器，走下面的流程
                // 拿到位置信息，去刷新抢单页面
                setTimeout(function(){
                    // 怕安卓页面还未加载到，给点延迟时间
                    api.sendEvent({
                        name: 'refreshGetOrderFrame',
                    });
                },500)
                clearInterval(tempTimer);
            }else{
                // 定位失败，记录失败次数
                tempSecond++
            }
            if(tempSecond >= 10){
                // 失败次数大于5秒（10次），则表示定位失败，提示定位失败逻辑
                clearInterval(tempTimer);
                api.execScript({
                    name: 'root',
                    frameName: 'get_order_frame',
                    script: 'evDoWithoutLngAndLat();'
                });
            }
        },500)
    };

    function getStaffLocationFrequently (staffData) {
        var GoogleMap = api.require('googleMap');
        GoogleMap.getLocation(function(ret) {
            if (ret.status) {
                $api.setStorage('staff_lng',ret.lon);
                $api.setStorage('staff_lat',ret.lat);
                api.ajax({
                    url: rootPath + '/api/staff/update_log_lat',
                    method: 'post',
                    data: {
                        values: { 
                            staff_id: staffData.id,
                            staff_token: staffData.token,
                            lng: ret.lon,
                            lat: ret.lat
                        },
                    }
                }, function(ret2, err2) {
                    
                });
            }
        });
    };

    function addSecond (second) {
        api.ajax({
            url: rootPath + '/api/staff/calculate_onlinetime',
            method: 'post',
            data: {
                values: { 
                    staff_id: staffData.id,
                    staff_token: staffData.token,
                    second: second
                },
            }
        }, function(ret, err) {
            if(ret && ret.status == 200){
                newestTime = ret.data.online_time;
                api.sendEvent({
                    name: 'updateMyIncome',
                    extra: {
                        onlineTime: ret.data.online_time, 
                        onlineMoney: ret.data.online_money,
                        total: ret.data.total,
                    }
                });
                api.sendEvent({
                    name: 'updateMyOnlineTime',
                    extra: {
                        totalTime: ret.data.online_time, 
                    }
                });
            }
        });
    }

    function calculateOnlineTime () {
        //每60秒记录一次,但是每秒要set一个interval因为骑手在线状态里是按照秒来算的
        var demo = api.require('myTimer');
        demo.startTimer({
            step:1,
            isLoop:true
        },function(ret) {
            if(ret){
                i++;
                if(i >= 60){
                    //每60秒记录一次到数据库
                    addOnlinetimePerMimute();
                    i = 0;
                }
            }
        });
    };


    function addOnlinetimePerMimute () {
        api.ajax({
            url: rootPath + '/api/staff/calculate_onlinetime',
            method: 'post',
            data: {
                values: { 
                    staff_id: staffData.id,
                    staff_token: staffData.token,
                },
            }
        }, function(ret, err) {
            if(ret && ret.status == 200){
                // 存入全局变量
                newestTime = ret.data.online_time;
                api.sendEvent({
                    name: 'updateMyIncome',
                    extra: {
                        onlineTime: ret.data.online_time, 
                        onlineMoney: ret.data.online_money,
                        total: ret.data.total,
                    }
                });
            }
        });
    };

    //监听推送具体函数
    function receive_fn(result) {
        console.log(result);
        // var a = JSON.stringify(data);
        var data = [];
        if(result && result.msg){
            var data = JSON.parse(result.msg);
        }
        if(data.todo == 'appoint_order'){
            var order_detail = JSON.parse(data.order_detail);
            // 后台指派订单
            api.sendEvent({
                name: 'appointOrder',
                extra: {
                    staffId: data.to, 
                    orderId: data.oid,
                    userAddress: order_detail.area_name2+order_detail.address_detail,
                    shopAddress: order_detail.shop_address,
                    shopDistance: order_detail.shop_distance,
                    rejectTime: order_detail.reject_time,
                    deliveryPrice: order_detail.delivery_price
                }
            });
        }else if(data.todo == 'shop_confirm_order'){
            // 商家确认了订单，需要把附近5公里的订单推送给骑手
            var shop = JSON.parse(data.shop);
            // 插入订单
            api.sendEvent({
                name: 'pushNewOrder',
                extra: {
                    shop: shop,
                }
            });
        }else if(data.todo == 'confirm_staff_order'){
            // 商家扫描骑手的二维码，需要修改骑手端订单状态
            var oid = data.oid;
            api.sendEvent({
                name: 'confirmStaffOrder',
                extra: {
                    oid: oid,
                }
            });
        }else if(data.todo == 'user_confirm_order'){
            // 用户确认收货后，需要修改骑手端订单状态
            var oid = data.oid;
            api.sendEvent({
                name: 'orderDeliverySuccess',
                extra: {
                    oid: oid,
                }
            });
            api.sendEvent({
                name: 'staffScanUserOrderSuccess',
            });
        }
    }

</script>




</html>